package com.example.fw;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;

public abstract class HelperBase {

	protected AppManager manager;
	protected WebDriver driver;
	public boolean acceptNextAlert = true;
	
	public HelperBase(AppManager manager) {
		this.manager = manager;
		this.driver = manager.driver;
	}
	
	public boolean isElementPresent(By by) {
	    try {
	      driver.findElement(by);
	      return true;
	    } catch (NoSuchElementException e) {
	      return false;
	    }
	  }

	public void type(By elementLocator, String inputText) {
		if (inputText != null) {
		  driver.findElement(elementLocator).clear();
		  driver.findElement(elementLocator).sendKeys(inputText);
		}
	}

	public void click(By elementLocator) {
		driver.findElement(elementLocator).click();
	}	
	
	public void changeComboBoxValue(By elementLocator, String value) {
		new Select(driver.findElement(elementLocator)).selectByVisibleText(value);
	}
		
	public boolean isAlertPresent() {
	    try {
	      driver.switchTo().alert();
	      return true;
	    } catch (NoAlertPresentException e) {
	      return false;
	    }
	  }

	public String closeAlertAndGetItsText() {
	    try {
	      Alert alert = driver.switchTo().alert();
	      String alertText = alert.getText();
	      if (acceptNextAlert) {
	        alert.accept();
	      } else {
	        alert.dismiss();
	      }
	      return alertText;
	    } finally {
	      acceptNextAlert = true;
	    }
	  }
}
